﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.LoginCommand;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace D.Medicalcare.Read.API.Application.Handler.LoginHandler
{
    /// <summary>
    /// 登录处理
    /// </summary>
    public class LoginHandler : IRequestHandler<LoginCommand, APIResult<User>>
    {
        private readonly IBaseRepository<User> urep;
        private readonly IConfiguration configuration;
        private readonly ILogger<LoginHandler> logger;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="urep"></param>
        /// <param name="logger"></param>
        public LoginHandler(IBaseRepository<User> urep, IConfiguration configuration, ILogger<LoginHandler> logger)
        {
            this.urep = urep;
            this.configuration = configuration;
            this.logger = logger;
        }
        /// <summary>
        /// 处理
        /// </summary>
        public Task<APIResult<User>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<User> result = new APIResult<User>();
            request.Pass = request.Pass.GetMD5();
            try
            {
                var model = urep.GetAll().FirstOrDefault(x => x.Name == request.Name);
                if (model != null)
                {
                    if (request.Pass != model.Pass)
                    {
                        result.Code = APIEnum.Failed;
                        result.Msg = "密码错误";
                        logger.LogError(result.Msg);

                    }
                    else
                    {
                        result.Code = APIEnum.Success;
                        result.Msg = "Bearer " + CreateTokenString(model.UserId,model.Name,model.Phone,model.WeChatName);
                        result.Data = model;
                        logger.LogInformation(result.Msg);
                    }

                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "账号不存在";
                    logger.LogError(result.Msg);
                }
                return Task.FromResult(result);

            }
            catch (Exception ex)
            {
                logger.LogError("登录异常"+ex.Message);

                throw;
            }
            
            
        }
        private string CreateTokenString(int UserId, string Name, string Phone, string WeChatName)
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(configuration["Jwt:SecretByte"]);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            var claims = new[]
            {
                new Claim("UserId",UserId.ToString()),
                new Claim("Name",Name),
                new Claim("Phone",Phone),
                new Claim("WeChatName",WeChatName)
            };
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: configuration["Jwt:ValidIssuer"],
                audience: configuration["Jwt:ValidAudience"],
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
    

}
